<?php
/**
 * Srun3000客户端类
 *
 * @author sskaje sskaje@gmail.com
 * @version 1.0.0
 * @todo 提供一个通信的机制
 */
class sscSrun3000forBIT 
{
	private $username;
	private $password;
	private $mode = 1;
	private $client_type = 1;
	private $n = 1;
	
	private $url_login     = 'http://10.0.0.55/cgi-bin/do_login';
	private $url_logout    = 'http://10.0.0.55/cgi-bin/do_logout';
	private $url_keepalive = 'http://10.0.0.55/cgi-bin/keeplive';
	
	private $modes = array(0=>'国际模式', 1=>'国内模式');
	private $client_types = array(1=>'WEB 模式', 2=>'客户端模式');

	private $user_agent = '';
	
	private $uid = 0;
	
	public  $debug = 0;
	/**
	 * cookie文件存放路径
	 *
	 * @var string
	 */
	private $cookie_file = 'cookie.txt';
	/**
	 * cURL 资源
	 *
	 * @var cURL
	 */
	private $ch;
	/**
	 * 构造函数，默认参数构造
	 *
	 * @param string $username 用户名
	 * @param string $password 密码
	 * @param int $mode        登陆模式，1->国内，0->国际
	 * @param int $client_type 客户端模式，1->Web，2->客户端
	 */
	public function __construct($username, $password, $mode=1, $client_type=1)
	{
		$this->username = $username;
		$this->password = $password;
		$this->change_mode($mode);
		$this->set_client_type($client_type);
	}
	/**
	 * 设置客户端模式
	 *
	 * @param int $client_type 客户端模式，1->Web，2->客户端
	 */
	public function set_client_type($client_type)
	{
		if ($client_type == 1)
		{
			$this->client_type = $client_type;
			$this->n = 1;
			$this->user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; GreenBrowser)';
		}
		else if ($client_type == 2)
		{
			$this->client_type = $client_type;
			$this->n = 3;
			$this->user_agent = 'my session';
		}
		else
		{
			throw new Exception('Bad client type');
		}
	}
	/**
	 * 设置登陆模式
	 *
	 * @param int $mode 登陆模式，1->国内，0->国际
	 */
	public function change_mode($mode)
	{
		if ($mode != 1 && $mode != 0)
		{
			throw new Exception('Bad login mode');
		}
		else if ($mode == 0)
		{
			echo "将以国际模式登陆\n";
		}
		else
		{
			echo "将以国内模式登陆\n";
		}
		$this->mode = $mode;
	}
	/**
	 * 设置cookie文件路径
	 *
	 * @param string $cookie_file
	 */
	public function set_cookie_fileloc($cookie_file)
	{
		$this->cookie_file = $cookie_file;
	}
	/**
	 * 初始化资源
	 *
	 */
	public function init()
	{
		$this->ch = curl_init();
		curl_setopt($this->ch, CURLOPT_VERBOSE, 0);
		curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($this->ch, CURLOPT_COOKIEJAR, $this->cookie_file);

		if ($this->client_type == 2)
		{
			curl_setopt($this->ch, CURLOPT_USERAGENT, 'my session');
			curl_setopt($this->ch, CURLOPT_PORT, 3333);
		}
		else
		{
			curl_setopt($this->ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; GreenBrowser) ');
		}
	}
	/**
	 * 登陆
	 *
	 */
	public function login()
	{
		if ($this->client_type == 2)
		{
			$password = $this->passencode($this->password);
		}
		else
		{
			$password = $this->password;
		}

		$login_str = 
			'username=' . urlencode($this->username) . 
			'&password=' . urlencode($password) . 
			'&drop=' . $this->mode . 
			'&type=' . $this->client_type . 
			'&n=' . $this->n;

		$this->debug('Login: ' . $login_str);

		curl_setopt($this->ch, CURLOPT_URL, $this->url_login);
		curl_setopt($this->ch, CURLOPT_REFERER, $this->url_login);
		curl_setopt($this->ch, CURLOPT_POST, 1);
		curl_setopt($this->ch, CURLOPT_POSTFIELDS, $login_str);
		$out = curl_exec($this->ch);

		$this->debug('Login response: ' . $out);

		curl_setopt($this->ch, CURLOPT_COOKIE, $this->username.'%7C'.$this->password);

		if (preg_match('#^\d+$#', $out))
		{
			$this->uid = $out;
			return;
		}
		$this->login_error($out);
	}
	/**
	 * 注销
	 *
	 */
	public function logout()
	{
		curl_setopt($this->ch, CURLOPT_URL, $this->url_logout);
		curl_setopt($this->ch, CURLOPT_POST, 1);
		$logout_str = 'uid='.$this->uid;
		
		$this->debug('Logout query: '.$logout_str);
		
		curl_setopt($this->ch, CURLOPT_POSTFIELDS, $logout_str);
		$out = curl_exec($this->ch);

		$this->debug('Logout: ' . $out);

		if ($out == 'logout_ok')
		{
			echo 'Successfully logout.';
		}
		else 
		{
			echo 'Failed to log u out';
		}
	}
	/**
	 * 保持连接
	 *
	 * @return string
	 */
	public function keepalive()
	{
		curl_setopt($this->ch, CURLOPT_URL, $this->url_keepalive);
		curl_setopt($this->ch, CURLOPT_POST, 1);
		$keepalive_str = 'uid='.$this->uid;
		
		$this->debug('Keepalive query: '.$keepalive_str);
		curl_setopt($this->ch, CURLOPT_POSTFIELDS, $keepalive_str);
		$out = curl_exec($this->ch);

		$this->debug('Keepalive: ' . $out);

		if (preg_match('#^\d+,\d+,\d+$#', $out))
		{
			return $out;
		}
		else
		{
			die('Disconnected.');
		}
	}

	/**
	 * 客户端模式密码加密
	 *
	 * @param string $pass
	 * @return string
	 */
	public function passencode($pass)
	{
		$atom = 70;
		$len = strlen($pass);
		for ($i=0; $i<$len; $i++)
		{
			$pass[$i] = chr(ord($pass[$i]) ^ $atom);
		}
		return $pass;
	}
	/**
	 * 登陆提示
	 *
	 * @param string $out
	 */
	public function login_error($out)
	{
		switch($out)
		{
		case "user_tab_error":
			die("认证程序未启动");
			break;
		
		case "username_error":
			die("用户名错误");
			break;
		
		case "non_auth_error":
			echo "您无须认证，可直接上网";
			break;
		
		case "password_error":
			die("密码错误");
			break;
		
		case "status_error":
			die("用户已欠费，请尽快充值。");
			break;
		
		case "available_error":
			die("用户已禁用");
			break;
		
		case "ip_exist_error":
			die("用户已存在");
			break;
		
		case "usernum_error":
			die("用户数已达上限");
			break;
		
		case "online_num_error":
			die("该帐号的登录人数已超过限额\n如果怀疑帐号被盗用，请联系管理员。");
			break;
		
		case "mode_error":
			die("系统已禁止WEB方式登录，请使用客户端");
			break;
		
		case "time_policy_error":
			die("当前时段不允许连接");
			break;
		
		case "flux_error":
			die("您的流量已超支");
			break;
		
		case "minutes_error":
			die("您的时长已超支");
			break;
		
		case "ip_error":
			die("您的IP地址不合法");
			break;
		
		case "mac_error":
			die("您的MAC地址不合法");
			break;
		
		default:
			die("找不到认证服务器");
			break;
		}
	}
	/**
	 * debug数据
	 *
	 * @param string $message
	 */
	public function debug($message)
	{
		if ($this->debug)
			echo "\n=====================================\n[DEBUG] ", date('Ymd H:i:s '), $message, "\n=====================================\n";
	}
	/**
	 * 查询状态
	 *
	 */
	public function query()
	{
		$msg = $this->keepalive();
		$nums = explode(',', $msg);
		echo "
Username: {$this->username}
UID     : {$this->uid}
Mode    : {$this->modes[$this->mode]}
Type    : {$this->client_types[$this->client_type]}

Data in : {$nums[1]} bytes
Data out: {$nums[2]} bytes
Connection time: {$nums[0]} seconds
";
	}
}